package apikey

import (
	"common/macaroon"
	"common/macaroon/pb"
	"common/uuid"
)

type ApiKeyConfig struct {
	secret []byte //从中心服务器读出来，保存到本地缓存。 每个project 唯一一个。 可以要求服务器重置，重置后所有apikey失效
}

func (a *ApiKeyConfig) NewApiKey(userid uuid.UUID) (*macaroon.APIKey, error) {
	return macaroon.NewAPIKey(userid, a.secret)
}

// NewApiKeyWithAllowPrefix 建一个只允许部分目录访问权限的apikey,  这里默认只读权限
func (a *ApiKeyConfig) NewApiKeyWithAllowPrefix(userid uuid.UUID, bucket string, encPrefix []byte, encKey []byte) (*macaroon.APIKey, error) {
	apikey, err := macaroon.NewAPIKey(userid, a.secret)
	if err != nil {
		return nil, err
	}
	err = apikey.AddLicense(&pb.License{
		Reads:   true,
		Writes:  false,
		Deletes: false,
		AllowedPaths: &pb.License_Path{
			Bucket:              []byte(bucket),
			EncryptedPathPrefix: encPrefix,
			EncryptedKey:        encKey,
		},
		NotAfter: 0,
	})
	if err != nil {
		return nil, err
	}
	return apikey, err
}
